package qmsz.api.service.traits;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import qmsz.api.utils.QMSZUtils;

public interface TWebPost {
	
	static final Logger logger = Logger.getLogger(TWebPost.class);

	/**
	 * 对目标URL发送POST请求。
	 * @param requestBody JSONObject形式的请求参数
	 * @param URL String形式的请求目标URL
	 * @return JSONObject形式的请求响应消息，如果为null，说明响应报文不是JSON格式
	 */
	default JSONObject postURL(JSONObject requestBody, String URL) {
		CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        JSONObject responseBody = null;
        try {
        	client = HttpClients.createDefault();
        	HttpPost post = new HttpPost(URL);
        	StringEntity entity = new StringEntity(requestBody.toJSONString(), "UTF-8");
        	entity.setContentEncoding("UTF-8");
        	entity.setContentType("application/json");
        	post.setEntity(entity);
        	response = client.execute(post);
        	HttpEntity valueEntity = response.getEntity();
        	String content = EntityUtils.toString(valueEntity);
        	responseBody = JSONObject.parseObject(content);
        } catch (Exception e) {
    		logger.error("response error", e);
    		responseBody = null;
        } finally {
        	QMSZUtils.tryClose(client, response);
        }
    	return responseBody;
	}
}
